﻿<html>
<head>
<title>Fiddler辅助工具  -- 2010清洁工版</title>
<hta:application
	applicationname="htanotepad" id="ohta" border="thick"
	borderstyle="normal" caption="yes" contextmenu="yes"
	innerborder="no" maximizebutton="yes" minimizebutton="yes"
	navigable="yes"
	icon="notepad.exe" scroll="no" scrollflat="no"
	selection="no" showintaskbar="yes" singleinstance="no"
	sysmenu="yes" version="0.3" windowstate="normal"/>
<script src="Common.js"></script>
<script src="Local.js"></script>
<style type="text/css">
body{margin:0;font-family:"宋体";font-size:12px;}
#textarea_editor{width:100%;height:100%;}
table,td,tr{width:100%;height:100%;}
.setting{height:25px;}
#text_path{width:500px;}
#text_url{width:300px;}
#text_filter{width:230px;}
.userData{behavior:url(#default#userdata);}
</style>
</head>
<body leftmargin="0" topmargin="0" rightmargin="0" scroll="no">
<table colspan="0" rowspan="0">
	<tr><td class="setting">
		本地目录：<input id="text_path" title="本地目录" class="userData"/><input id="button_path" type="button" value="选择目录"/>&nbsp;<input id="button_close" type="button" value="退出"/>
	</td></tr>
	<tr><td class="setting">
		站点路径：<input id="text_url" title="站点路径" class="userData"/>&nbsp;&nbsp;过滤正则：<input id="text_filter" title="过滤正则" class="userData"/>
	</td></tr>
	<tr><td class="setting">
		<input id="button_process" type="button" value="映射"/>&nbsp;<input id="button_clear" type="button" value="清理无效的配置"/>&nbsp;<label><input id="button_ignorePort" type="checkbox" checked="checked"/>忽略端口</label>
	</td></tr>
	<tr><td class="setting">
		<input id="button_clearLog" type="button" value="清除日志"/>&nbsp;
	</td></tr>
	<tr><td>
		<textarea id="textarea_editor" wrap="off"></textarea>
	</td><tr>
</table>
<script type="text/javascript">
function fiddlerExists() {
	var locator = new ActiveXObject("WbemScripting.SWbemLocator");
	var service = locator.ConnectServer(".", "/root/CIMV2");
	var processes = service.ExecQuery("select * from Win32_Process where name like 'fiddler%.exe'");
	var count = -1;
	try {
		count = processes.count;
	} finally {
		locator = null;
		service = null;
		processes = null;
	}
	return count;
}

Common.setEvent(window, "load", function() {
	try {
		Common.$("text_path").load("path");
		Common.$("text_path").value = Common.$("text_path").getAttribute("path") || ""; 
		Common.$("text_url").load("url");
		Common.$("text_url").value = Common.$("text_url").getAttribute("url") || "http://www.baidu.com"; 
		Common.$("text_filter").load("filter");
		Common.$("text_filter").value = Common.$("text_filter").getAttribute("filter") || "\\.(html|js|css|htm|gif|jpg|png|ico)$"; 
	} catch(ex) {
	}
	Common.$("button_close").onclick = function() {
		window.close();
	};

	var shell = new ActiveXObject("WScript.Shell");
	var fiddlerFile = shell.SpecialFolders("MyDocuments") + "\\Fiddler2\\AutoResponder.xml";
	shell = null;
	if (!Local.fileExists(fiddlerFile)) {
		alert('请确认您的机器已经安装了fiddler2');
		return;
	}
	
	Common.$("button_path").onclick = function() {
		var folder = Local.folderDialog("请选择路径");
		if (!folder) return;
		Common.$("text_path").value = folder;
	};
	Common.$("button_process").onclick = function() {
		if (fiddlerExists()) {
			alert("请先关闭fiddler程序。");
			return;
		}
		var error = "";
		Common.$("text_path").value = Common.$("text_path").value.replace(/[\/]$/, "");
		Common.$("text_url").value = Common.$("text_url").value.replace(/[\/]$/, "");
		if (!Local.folderExists(Common.$("text_path").value)) {
			error += Common.format("${0} \"${1}\" 不存在。\n",
				[Common.$("text_path").title, Common.$("text_path").value]);
		}
		Common.$("text_path").setAttribute("path", Common.$("text_path").value); 
		Common.$("text_path").save("path");
		
		if (!/^https?:\/\//i.test(Common.$("text_url").value)) {
			error += Common.format("${0} \"${1}\" 格式不正确。\n",
				[Common.$("text_url").title, Common.$("text_url").value]);
		}
		Common.$("text_url").setAttribute("url", Common.$("text_url").value); 
		Common.$("text_url").save("url");
		
		try {
			var filter = new RegExp(Common.$("text_filter").value, "i");
		} catch(ex) {
			error += Common.format("${0} \"${1}\" ${2} 。\n", 
				[Common.$("text_filter").title, Common.$("text_filter").value, ex.message]);
		}
		Common.$("text_filter").setAttribute("filter", Common.$("text_filter").value); 
		Common.$("text_filter").save("filter");
		
		if (error) {
			alert(error);
			return;
		}
		var xmldocument = new ActiveXObject("MSXML2.DOMDocument");
		xmldocument.load(fiddlerFile);
		var state = xmldocument.selectSingleNode("AutoResponder/State");
		if (!state) {
			alert("没有发现节点 \"AutoResponder/State\"");
			return;
		}
		var count = 0;
		var length = Common.$("text_path").value.length;
		Local.scanFolder(Common.$("text_path").value, function(filename) {
			if (!filter.test(filename)) return;
			var url = Common.$("text_url").value + filename.substring(length).replace(/\\/g, "/");
			url = url.replace(/[^\x00-\xff]/g, function($0) {
				return encodeURI($0);
			})
			if (Common.$("button_ignorePort").checked) // 是否忽略
				url = url.replace(/^(http:\/\/[^\/]+)/g, "$1\x00");
			var match = Common.format("regex:(?insx)^${0}",
				[Common.regEscape(url)]).replace(/\x00/, "(:\\d+)?");
			var node = xmldocument.selectSingleNode(
				Common.format("AutoResponder/State/ResponseRule[@Match=\"${0}\"]", [match.replace(/\\/g, "\\\\")]));
			if (node) {
				Common.$("textarea_editor").value += Common.format("Match:${0} 已经存在。\n",
					[match]);
				return;
			}
			var child = state.appendChild(xmldocument.createElement("ResponseRule"));
			child.setAttribute("Match", match);
			child.setAttribute("Action", filename);
			child.setAttribute("Enabled", "true");
			Common.$("textarea_editor").value += Common.format("Match:${0} Action:${1}\n",
				[match, filename]);
			count++;
			
		});
		if (count) xmldocument.save(fiddlerFile); // 存在变化
	};
	
	Common.$("button_clearLog").onclick = function() {
		Common.$("textarea_editor").value = "";
	};
	
	Common.$("button_clear").onclick = function() {
		if (fiddlerExists()) {
			alert("请先关闭fiddler程序。");
			return;
		}

		var xmldocument = new ActiveXObject("MSXML2.DOMDocument");
		xmldocument.load(fiddlerFile);
		var responseRules = xmldocument.selectNodes("AutoResponder/State/ResponseRule");
		if (!responseRules) {
			alert("没有发现节点 \"AutoResponder/State/ResponseRule\"");
			return;
		}
		var count = 0;
		var matches = [];
		var matchDict = {};
		for (var i = 0; i < responseRules.length; i++) {
			var rule = responseRules[i];
			var filename = rule.getAttribute("Action");
			if (!/^[a-z]:/i.test(filename) || Local.fileExists(filename)) {
				var match = rule.getAttribute("Match");
				if (matchDict[match]) {
					if (matchDict[match] == 1) matches.push(match);
					matchDict[match]++;
				}
				matchDict[match] = 1;
				continue;
			}
			rule.parentNode.removeChild(rule);
			Common.$("textarea_editor").value += Common.format("Match:${0} 被清理，原因：${1} 不存在。\n",
				[rule.getAttribute("Match"), filename]);
			count++;
		}
		for (var i = 0; i < matches.length; i++) {
			var matche = matches[i];
			var nodes = xmldocument.selectNodes(
				Common.format("AutoResponder/State/ResponseRule[@Match=\"${0}\"]", [matche.replace(/\\/g, "\\\\")]));
			for (var j = 1; j < nodes.length; j++) {
				var node = nodes[j];
				Common.$("textarea_editor").value += Common.format("Match:${0} 被清理，原因：重复。\n",
					[node.getAttribute("Match")]);
				node.parentNode.removeChild(node);
			}
		}
		if (count) xmldocument.save(fiddlerFile); // 存在变化
	}
});
</script>
</body>
</html>